import { cancelOrder } from '@/api/order'
const timeValue = 15 * 60 * 1000

function setCountDown(orderNum: string) {
  const orderList = JSON.parse(localStorage.getItem('orderList') || 'null')
  if (orderList === null) {
    const orderArr = []
    orderArr.push(orderNum)
    localStorage.setItem('orderList', JSON.stringify(orderArr))
  } else {
    orderList.push(orderNum)
    localStorage.setItem('orderList', JSON.stringify(orderList))
  }
  const timer = Date.now() + timeValue
  localStorage.setItem(`${'orderCountDown' + orderNum}`, timer.toString())
}
function checkCountDown() {
  const nowTimer = Date.now()
  const orderList = JSON.parse(localStorage.getItem('orderList') || 'null')
  orderList &&
    orderList.forEach((item: any, i: number) => {
      const timer = Number(localStorage.getItem(`${'orderCountDown' + item}`))
      if (nowTimer - timer > timeValue) {
        localStorage.removeItem(`${'orderCountDown' + item}`)
        cancelOrder(item)
        orderList.splice(i, 1)
        localStorage.setItem('orderList', JSON.stringify(orderList))
      }
    })
}

export default { setCountDown, checkCountDown }
